package com.tiankun.eurekauserinfo.service.impl;


import com.tiankun.eurekauserinfo.exception.BusinessException;
import com.tiankun.eurekauserinfo.service.ShoppingCartService;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created with IntelliJ IDEA
 * User: bear
 * Date: 2020/11/13
 * Description
 * Version: V1.0
 */
@Service(value = "shoppingCartService")
@Transactional
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Resource
    RedisTemplate redisTemplate;

    @Override
    public Long addShop(String phone, Integer shopId, Integer number) {
        if (shopId == null) {
            throw new BusinessException("请选择型号");
        }
        if (number == null || number == 0) {
            throw new BusinessException("商品数量不能为0");
        }
        //将数据保存在redis服务器上,
        //1.利用redisTemplate去绑定要操作的数据类型,生成对应的操作符
        //对redis的hash类型进行操作
        HashOperations hashOperations = redisTemplate.opsForHash();
        //hset操作
        //                              名字（区分用户）    键（商品id）              值（商品数量）
        return hashOperations.increment("shop" + phone, String.valueOf(shopId), (long) number);
    }


    @Override
    public Map<String, Object> getList(String userPhone) {

        if (userPhone == null) {
            //对电话号码进行校验，如果为空，抛出异常
            throw new BusinessException("电话号码不能为空");
        }
        HashOperations hashOperations = redisTemplate.opsForHash();
        //取出user添加购物车的所有shopId
        Set<String> godIds = hashOperations.keys("shop" + userPhone);

        //取出键值对 shopId和number
        Map entries = hashOperations.entries("shop" + userPhone);

        Map<String, Object> map = new HashMap<>();
        map.put("godIds", godIds);
        map.put("entries", entries);

        return map;
    }

    @Override
    public void deleteList(List<Integer> list, String userPhone) {
        HashOperations hashOperations = redisTemplate.opsForHash();
        for (Integer i : list) {
            //删除redis 上的商品id
            hashOperations.delete("shop" + userPhone, String.valueOf(i));
        }
    }

}
